package com.flyee.viewer.pack.helper
{
	import com.flyee.events.SelectionEvent;
	import com.flyee.utils.MyLog;
	
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.text.TextField;
	
	import mx.containers.Canvas;
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.core.UIComponent;
	import mx.events.CloseEvent;

	public class PackageContainer extends Canvas
	{
		/**
		 * 包裹面板的宽和高
		 */
		private var packWidth:int=330;
		private var packHeight:int=0;
		/**
		 * 垂直和水平间隔
		 */
		private const V_GAP:int=5;
		private const H_GAP:int=5;
		/**
		 * 切换、添加包裹按钮的容器
		 */
		private var btnsContainer:UIComponent=null;
		private var itemCount:int=5;
		[ArrayElementType("UIComponent")]
		private var itemList:Array=null;
		/**
		 * 货币容器
		 */
		private var coinContainer:UIComponent=null;
		/**
		 * 放道具的容器列表
		 */
		[ArrayElementType("ItemsContainer")]
		private var propsList:Array=null;
		/**
		 * 所有道具的显示容器
		 */
		private var itemsBox:Canvas=null;
		/**
		 * 当前选择的包裹面板
		 */
		private var currentProps:ItemsContainer=null;
		/**
		 * 上一次的道具面板
		 */
		private var oldProps:ItemsContainer=null;
		/**
		 * 当前选择的道具
		 */
		private var selectedItem:ItemViewModel=null;
		private var goldCoinLab:TextField=null;
		private var blueCoinLab:TextField=null;
		private var goldCoin:Number=2046;
		private var blueCoin:Number=2046;
		
		[Embed(source="resource/goldIcon.png")]
		private var GoldIcon:Class;
		[Embed(source="resource/blueIcon.png")]
		private var BlueIcon:Class;
		//private var packageHelper:PackageHelper=null;

		/**
		 * 多包裹容器，可以包含多个ItemsContainer组件
		 *
		 */
		public function PackageContainer()
		{
			super();
			init();
		}

		private function init():void
		{
			itemsBox=new Canvas();
			initItemsPanel();
			initCoinPanel();
			//packageHelper=new PackageHelper(this);
			showPack(0);
			var temp:ItemsContainer=propsList[0];
			packWidth=temp.sizeWH.x;
			//itemsBox.x = (packWidth - btnsContainer.width) / 2;
			//btnsContainer.y = 5;
			itemsBox.y=5;
			coinContainer.y=temp.sizeWH.y + 15;
			coinContainer.x=packWidth + 20 - 130;
			//packHeight = packHeight + btnsContainer.height + coinContainer.height + 22;
			this.addChild(coinContainer);
			this.addChild(itemsBox);
			packHeight=temp.sizeWH.y + 45;
		//this.addChild(btnsContainer);
		}

		/**
		 * 初始化包裹切换按钮面板
		 *
		 */
		private function initItemsPanel():void
		{
			btnsContainer=new UIComponent();
			itemList=new Array(itemCount);
			propsList=new Array();
			var totalCells:int=0;

			for(var i:int=0; i < itemCount; i++)
			{
				var btnContainer:Sprite=new Sprite();

				var props:ItemsContainer=null;

				if (i > 1)
				{
					//button = BitmapdataDepot.getSimpleButton("AddPackButton");
					btnContainer.name="addpack";
				}
				else
				{
					//button = BitmapdataDepot.getSimpleButton("PackButton");
					props=new ItemsContainer(7, 8);
					props.addEventListener(SelectionEvent.SELECTED, selectHandler);
					props.addEventListener(SelectionEvent.BUY_PROP, reduceCoinHandler);
					props.addEventListener("refreshPackage",refreshPackageEvent);
					props.name=i + "pack";
					props.packIndex=i;
					btnContainer.name=i + "packbtn";
					propsList.push(props);
					totalCells+=props.cellCount;
				}
				//btnContainer.addChild(button);
				btnContainer.x=i * 50;
				//btnContainer.addEventListener(MouseEvent.CLICK, clickHandler);
				itemList[i]=btnContainer;
				//btnsContainer.addChild(btnContainer);
			}
			PackageHelper.TOTAL_COUNT=totalCells;
		}

		/**
		 * 初始化游戏币按钮
		 *
		 */
		private function initCoinPanel():void
		{
			var coin1:Bitmap=new GoldIcon();
			var coin2:Bitmap=new BlueIcon();
			coinContainer=new UIComponent();
			//coin1.bitmapData = BitmapdataDepot.getBitmapData("GoldLogo");
			//coin2.bitmapData = BitmapdataDepot.getBitmapData("BlueLogo");
			goldCoinLab=createLab(goldCoin.toString());
			blueCoinLab=createLab(blueCoin.toString());
			coin1.x=5;
			coin2.x=65;
			goldCoinLab.x=26;
			blueCoinLab.x=86;
			coinContainer.addChild(coin1);
			coinContainer.addChild(coin2);
			coinContainer.addChild(goldCoinLab);
			coinContainer.addChild(blueCoinLab);
		}

		private function isContains(name:String):Boolean
		{
			var temp:DisplayObject=this.getChildByName(name);

			if (temp)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		
		private function refreshPackageEvent(event:Event):void{
			var target:ItemsContainer = event.currentTarget as ItemsContainer;
			target.refresh();
			//packageHelper.getItemInPackage();
		}

		private function selectHandler(e:SelectionEvent):void
		{
			var propCase:ItemsContainer=e.currentTarget as ItemsContainer;
			var prop:ItemViewModel=e.entity as ItemViewModel;

			if (prop != selectedItem)
			{
				selectedItem=prop;
			}
			prop.addEventListener(SelectionEvent.STOPMOVE_PROP, stopDragHandler, false, 0, true);
		}

		private function stopDragHandler(event:SelectionEvent):void
		{

			if (selectedItem)
			{
				var prop:ItemViewModel=selectedItem;
				var container:ItemsContainer=null;
				//var btn:Sprite = null;
				var i:int=0;
				var oldContainer:ItemsContainer=null;

				/* 	for(i = 0; i < 5; i++)
				   {
				   btn = itemList[i];

				   if (btn.hitTestPoint(Main.getMainUI().stage.mouseX, Main.getMainUI().stage.mouseY, true))
				   {
				   var tempName:String = btn.name;

				   if (currentProps)
				   {
				   changePack(tempName);
				   }
				   }
				 } */

				if (currentProps)
				{
					//道具碰撞到包裹容器
					if (currentProps.hitTestPoint(Application.application.stage.mouseX, Application.application.stage.mouseY, true))
					{
						prop.stopDrag();
						var accross:Boolean=currentProps.fillCell(prop, goldCoin, blueCoin);

						//accross=true表示是该道具是从别的包裹拖动到现在的包裹中
						if (accross && oldProps.packIndex != currentProps.packIndex)
						{
							oldProps.removeProp(prop);
							oldProps=currentProps;
						}
						selectedItem=null;
						prop.removeEventListener(SelectionEvent.STOPMOVE_PROP, stopDragHandler);
					}
					else
					{
						//自己包裹里的道具拖动到包裹外面
						if (!selectedItem.dataModel.isSystem)
						{
							var count:int=selectedItem.dataModel.currentCapability;

							if (count > 1)
							{
								//可以销毁多个道具
								/* var numStepper:NumberStepperBox=new NumberStepperBox();
								numStepper.tipMessage="请输入摧毁的数量：";
								numStepper.maxCount=count;
								numStepper.addEventListener(SelectionEvent.SPLIT_PROP, numInputSureEvent, false, 0, true);
								numStepper.addEventListener(CloseEvent.CLOSE, numInputCloseEvent, false, 0, true);
								numStepper.x=(this.parent.width - numStepper.width) / 2;
								numStepper.y=(this.height - numStepper.height) / 2;
								this.addChild(numStepper); */
							}
							else
							{
								//只有一个道具供销毁
								Alert.okLabel="确定";
								Alert.cancelLabel="取消";
								Alert.show("是否删除该道具？", "提示", Alert.OK | Alert.CANCEL, this.parent as Sprite, requestRemoveItems);
							}
						}
					}
				}
			}
		}

		/* private function numInputCloseEvent(event:Event):void
		{
			var target:NumberStepperBox=event.currentTarget as NumberStepperBox;
			target.clearAll();
			this.removeChild(target);
			target=null;
		} */

		/**
		 * 摧毁多个道具时，数字输入后的确定处理
		 * @param e
		 *
		 */
		/* private function numInputSureEvent(event:SelectionEvent):void
		{
			var num:int=parseInt(event.key);
			var target:NumberStepperBox=event.currentTarget as NumberStepperBox;
			target.clearAll();
			this.removeChild(target);
			target=null;
			MyLog.debug("destroy multi props..." + num);

			if (selectedItem)
			{
				var count:int=selectedItem.dataModel.currentCapability;

				if (num < count && num > 0)
				{
					//当摧毁的个数小于当前的数量时
					//destroyMultiProps(selectedItem,num);
					var itemid:String=selectedItem.dataModel.id;
					var position:int=selectedItem.dataModel.currentPosistion;
					packageHelper.removeItem(itemid, position, num);
				}
				else if (num == count)
				{
					//当摧毁的个数等于当前数量时
					requestRemoveItems(null);
				}
				else
				{
				}
				selectedItem=null;
			}
		} */

		/**
		 * 摧毁一个道具的服务器请求
		 * @param tag
		 *
		 */
		private function requestRemoveItems(event:CloseEvent):void
		{
			var tag:Boolean = false;
			if (event)
			{
				if (event.detail == Alert.OK)
				{
					tag = true;
				}
				else if (event.detail == Alert.CANCEL)
				{
					ItemViewModel.dragSprite=null;
					tag = false;
				}
			}
			else
			{
				tag = true;
			}
			if(tag){
				if (selectedItem)
				{
					var itemid:String=selectedItem.dataModel.id;
					var pos:int=selectedItem.dataModel.currentPosistion;
					var count:int=selectedItem.dataModel.currentCapability;
					//packageHelper.removeItem(itemid, pos, count);
				}
			}
		}

		/**
		 * 摧毁一个格子中的多个道具
		 * @param result
		 *
		 */
		private function destroyMultiItems(item:ItemViewModel, remainCount:int):void
		{
			if (currentProps)
			{
				var div:int=item.dataModel.currentCapability - remainCount;
				currentProps.reduceStackCount(item.name, div);
			}
			if (selectedItem)
			{
				selectedItem.dispose();
			}
			selectedItem=null;
			ItemViewModel.dragSprite=null;
		}

		/**
		 * 摧毁一组道具,即一个格子中的所有道具
		 * @param data
		 *
		 */
		private function destroyGroupItems(item:ItemViewModel):void
		{
			MyLog.debug("destroy one prop in package..." + item.dataModel.id);

			if (currentProps)
			{
				currentProps.removeProp(item);
			}
			if (selectedItem)
			{
				selectedItem.dispose();
			}
			selectedItem=null;
			ItemViewModel.dragSprite=null;
		}

		/**
		 * 根据itemid和绝对位置从当前所有包裹中查找道具
		 * @param id
		 * @param pos
		 * @return
		 *
		 */
		private function getItemByPosition(id:String, pos:int):ItemViewModel
		{

			for(var i:int=0; i < propsList.length; i++)
			{
				var props:ItemsContainer=propsList[i]as ItemsContainer;
				return props.getItemByPosition(id,pos);
				/* var items:Array=props.getCurrentItems();
				var prop:ItemViewModel=null;

				//从每个包裹中查找当前包裹中的道具的最初绝对位置和pos相同且交易ID也相同的道具				
				if (items)
				{

					for(var j:int=0; j < items.length; j++)
					{
						var temp:ItemViewModel=items[j];

						if (pos == temp.dataModel.initPosition && id == temp.dataModel.id)
						{
							prop=temp;
							break;
						}
					}

					//当找到后就跳出循环
					if (prop)
					{
						return prop;
					}
				} */
			}
			return null;
		}

		/**
		 * 减少金币
		 * @param e
		 *
		 */
		private function reduceCoinHandler(event:SelectionEvent):void
		{
			var cityCoin:int = parseInt(event.key);
			var goldCoin:int = parseInt(event.value);
			setBlueCoin(blueCoin - cityCoin);
			setGoldCoin(goldCoin - goldCoin);
		}

		/* private function clickHandler(e:MouseEvent):void
		   {
		   var btn:Sprite = e.currentTarget as Sprite;
		   var tempName:String = btn.name;

		   if (currentProps)
		   {
		   changePack(tempName);
		   }
		 } */

		/**
		 * 切换包裹
		 * @param name
		 *
		 */
		private function changePack(name:String):void
		{
			var index:int=0;
			var title:String=name;

			if (currentProps.name == title)
			{
			}
			else
			{

				if (title == "addpack")
				{
					trace("add one pack to panel");
				}
				else
				{
					//trace(index +"::" +name);
					index=parseInt(title.charAt(0));

					for(var i:int=0; i < itemCount - 1; i++)
					{
						var temp:Sprite=itemList[i]as Sprite;

						if (i == index)
						{
							//showPackButton(temp, true);
							showPack(i);
						}
						else
						{
							//showPackButton(temp, false);
						}
					}
				}
			}
		}

		private function showPack(tag:int):void
		{
			currentProps=null;

			while(itemsBox.numChildren > 0)
			{
				itemsBox.removeChildAt(0);
			}
			var props:ItemsContainer=propsList[tag]as ItemsContainer;
			currentProps=props;

			if (!oldProps || !selectedItem)
			{
				oldProps=props;
			}
			itemsBox.addChild(props);
		}

		/**
		 * 显示包裹按钮的状态
		 * @param tag
		 * @param isOpen
		 *
		 */ /* private function showPackButton(tag:Sprite, isOpen:Boolean):void
		   {

		   while(tag.numChildren > 0)
		   {
		   tag.removeChildAt(0);
		   }

		   if (isOpen)
		   {
		   tag.addEventListener(MouseEvent.MOUSE_OVER, clickHandler);
		   tag.addChild(BitmapdataDepot.getSimpleButton("OpenPackButton"));
		   }
		   else
		   {
		   tag.removeEventListener(MouseEvent.MOUSE_OVER, clickHandler);
		   tag.addChild(BitmapdataDepot.getSimpleButton("PackButton"));
		   }
		 } */

		private function createLab(name:String):TextField
		{
			var txt:TextField=new TextField();
			txt.selectable=false;
			txt.text=name;
			txt.height=20;
			txt.y=2;
			//txt.textColor = 0xffffff;
			//ColorMagicOfText.bewrite(txt);
			return txt;
		}

		/**
		 * 摧毁多个道具或者一组道具
		 * @param itemData
		 *
		 */
		public function destroyItems(itemData:ItemDataModel):void
		{
			var item:ItemViewModel=getItemByPosition(itemData.id, itemData.currentPosistion);
			if (item)
			{
				if (itemData.currentCapability > 0)
				{
					//该位置还有道具，没有全部删除
					destroyMultiItems(item, itemData.currentCapability);
				}
				else
				{
					//该位置没有道具，全部删除
					destroyGroupItems(item);
				}
			}
			else
			{
				Alert.show("数据异常，建议关闭包裹后再重新打开！", "异常");
			}
		}

		public function setGoldCoin(coin:Number):void
		{
			goldCoin=coin;
			goldCoinLab.text=goldCoin.toString();
		//var char:Character = SceneManager.getCharacterSprite(Character.masterID);
		//char.goldCoin = coin;
		}

		public function getGoldCoin():Number
		{
			return goldCoin;
		}

		public function hasDragged():ItemsContainer
		{

			for(var i:int=0; i < propsList.length; i++)
			{
				var temp:ItemsContainer=propsList[i]as ItemsContainer;

				if (temp.hasDragged())
				{
					return temp;
				}
			}
			return null;
		}

		public function setBlueCoin(coin:Number):void
		{
			blueCoin=coin;
			blueCoinLab.text=blueCoin.toString();
		//var char:Character = SceneManager.getCharacterSprite(Character.masterID);
		//char.blueCoin = coin;
		}

		public function getBlueCoin():Number
		{
			return blueCoin;
		}

		/**
		 * 向包裹中添加一个道具
		 * @param prop
		 *
		 */
		public function updateOneProp(prop:ItemViewModel):void
		{
			var temp:ItemsContainer=null;
			//确定该道具是属于哪一个包裹的（现在只有一个包裹）
			var index:int=prop.dataModel.packPanelIndex;
			var item:ItemViewModel=prop;

			if (index < propsList.length)
			{
				//得到该包裹的实例引用
				temp=propsList[index]as ItemsContainer;
				//把道具放到该包裹中
				var flag:Boolean=temp.updateProp(prop);
				if (flag)
				{
					return ;
				}
				else
				{
					//该包裹已经满了，自动放到第二个包裹，（递归）
					item.dataModel.packPanelIndex=index + 1;
					updateOneProp(item);
				}
			}
			else
			{
				return ;
			}
		}

		/**
		 * 向道具面板中添加一个道具
		 * @param prop
		 *
		 */
		public function addOneProp(prop:ItemViewModel):void
		{
			var temp:ItemsContainer=null;
			var index:int=prop.dataModel.packPanelIndex;

			if (index < propsList.length)
			{
				temp=propsList[index]as ItemsContainer;
				temp.addProp(prop, prop.dataModel.currentPosistion);
			}
		/* for(var i:int = 0;i < propsList.length;i++){
		   temp = propsList[i] as ItemsContainer;
		   if(temp.getEmptyIndex() > -1){
		   break;
		   }
		 } */
		}

		/**
		 * 清除一个道具
		 * @param id
		 * @return
		 *
		 */
		public function removeOneProp(id:String, pos:int):Boolean
		{
			var prop:ItemViewModel=getItemByPosition(id, pos);

			if (prop)
			{
				MyLog.debug("find used prop..." + prop.name);
				//得到该道具所在的当前包裹面板索引
				var index:int=prop.dataModel.packPanelIndex;

				if (index < propsList.length)
				{
					//得到当前包裹面板中的实例引用
					var props:ItemsContainer=propsList[index]as ItemsContainer;
					return props.removeUsingProp(prop.dataModel.currentPosistion);
				}
			}
			return false;
		}

		/**
		 * 打开可以使用的开关
		 * @param id
		 * @param pos
		 * @return
		 *
		 */
		public function openUsingLimit(id:String, pos:int):Boolean
		{
			var prop:ItemViewModel=getItemByPosition(id, pos);

			if (prop)
			{
				var index:int=prop.dataModel.packPanelIndex;

				if (index < propsList.length)
				{
					var props:ItemsContainer=propsList[index]as ItemsContainer;
					return props.openUsingLimit(prop.dataModel.currentPosistion);
				}
			}
			return false;
		}

		/**
		 * 判断包裹是否满了
		 * @return
		 *
		 */
		public function isFull():Boolean
		{

			for(var i:int=0; i < propsList.length; i++)
			{
				var temp:ItemsContainer=propsList[i]as ItemsContainer;

				if (!temp.isFull())
				{
					return false;
				}
			}
			return true;
		}

		/**
		 * 获取该面板的宽和高
		 * @return
		 *
		 */
		public function get sizeWH():Point
		{
			return new Point(packWidth + 40, packHeight + 40);
		}

		/* public function getSaveXML():XML
		   {
		   var root:XML = CreateXMLNode.getRootNode("package");

		   for(var i:int = 0; i < propsList.length; i++)
		   {
		   var props:ItemsContainer = propsList[i]as ItemsContainer;
		   var items:Array = props.getSaveItems();

		   if (items)
		   {

		   for(var j:int = 0; j < items.length; j++)
		   {
		   var prop:AbstractProp = items[j]as AbstractProp;
		   var index:int = prop.dataModel.cellIndex + i * PackMainPanel.AVERAGE_COUNT;
		   var oldpos:int = prop.dataModel.initCellIndex;
		   var item:XML = processor.getSingleItemXML(index, oldpos, 0, 0);
		   root.appendChild(item);
		   }
		   }
		   }
		   return root;
		 } */

		public function getCurrentCells():Array
		{

			if (currentProps)
			{
				return currentProps.getCells();
			}
			return null;
		}

		public function clearCellsData():void
		{
			var i:int=0;
			var props:ItemsContainer=null;

			for(i=0; i < propsList.length; i++)
			{
				props=propsList[i]as ItemsContainer;
				props.refresh();
			}
		}

		public function clearAll():void
		{
			var i:int=0;
			var props:ItemsContainer=null;
			selectedItem=null;
			currentProps=null;
			itemsBox=null;

			while(btnsContainer.numChildren > 0)
			{
				btnsContainer.removeChildAt(0);
			}

			if (itemList)
			{
				itemList.splice(0);
				itemList=null;
			}

			for(i=0; i < propsList.length; i++)
			{
				props=propsList[i]as ItemsContainer;
				props.removeEventListener(SelectionEvent.SELECTED, selectHandler);
				props.clearAll();
			}
			//packageHelper.clearAll();
			//packageHelper=null;
			blueCoinLab=null;
			goldCoinLab=null;
		}

	}
}



